var express = require("express");
var router = express.Router();
var fs = require("fs");
const path = require("path");
/**
 * @api {post} /api/v1/delectImg Request delect Img
 * @apiGroup Delect
 * @apiName delectImg
 * @apiParam {Array} deleImgArr: []
 */
//删除富文本图片
router.post("/api/v1/delectImg", function(req, res, next) {
  let deleImgArr = req.body.deleImgArr;
  console.log(deleImgArr);
  if (deleImgArr.length != 0) {
    deleImgArr.forEach(item => {
      console.log(item);
      fs.unlink(
        path.join(__dirname, "../public/images/fwImg/" + item),
        function(error) {
          if (error) {
            console.log(error);
            return false;
          }
          console.log("删除文件成功");
        }
      );
    });
  }
  res.json({
    code: 200
  });
});

/**
 * @api {post} /api/v1/enclosure Request delect enclosure
 * @apiGroup Delect
 * @apiName delectEnclosure
 * @apiParam {Array} deleArr: []
 */
//删除附件
router.post("/api/v1/enclosure", function(req, res, next) {
  let deleArr = req.body.deleArr;
  console.log(deleArr);
  if (deleArr.length != 0) {
    deleArr.forEach(item => {
      console.log(item);
      fs.unlink(path.join(__dirname, "../public/enclosure/" + item), function(
        error
      ) {
        if (error) {
          console.log(error);
          return false;
        }
        console.log("删除文件成功");
      });
    });
  }
  res.json({
    code: 200
  });
});

const jsdom = require("jsdom");
const JSDOM = jsdom.JSDOM;
const document = new JSDOM().window.document;

const rich_text_img_prefix = `https://jifen.zhportinfo.com/images/fwImg/`;

//获取富文本图片id
const getRemovImgId = html => {
  let dom = document.createElement("DIV");
  dom.innerHTML = html;
  const imgDom = dom.getElementsByTagName("img");
  // const url = window.location.host;
  const arr = [];

  for (let i = 0; i < imgDom.length; i++) {
    let name = imgDom[i].src.replace(rich_text_img_prefix, "");
    arr.push(name);
  }
  return arr;
};

let article = require("../model/article");
let resource = require("../model/resource");
let answer = require("../model/answer");
let comment = require("../model/comment");
let comfabulous = require("../model/comfabulous");
let recommend = require("../model/recommend");
let history = require("../model/history");
let articleOnlineDraft = require("../model/articleOnlineDraft");
let resourceOnlineDraft = require("../model/resourceOnlineDraft");
let answerOnlineDraft = require("../model/answerOnlineDraft");

//删除文章（回答）
router.post("/api/v1/delectAnswer", async function(req, res, next) {
  let deleData = req.body;
  try {
    //文章图片
    let htmlDelectId = getRemovImgId(deleData.content);

    //删除并找出线上文章
    let answerOnlineDraftData = await answerOnlineDraft.findOneAndDelete({
      articleId: deleData._id
    });

    let onlineDele = [];
    if (answerOnlineDraftData) {
      let onliveHtmlDelectId = getRemovImgId(answerOnlineDraftData.content);
      onlineDele = answerOnlineDraftData.deleImgId.concat(
        answerOnlineDraftData.deleImgId,
        onliveHtmlDelectId
      );
    }
    console.log(answerOnlineDraftData);

    //总图片
    let allDelect = onlineDele.concat(htmlDelectId);

    //去重
    let selectAllDel = [...new Set(allDelect)];
    //删除图片
    if (selectAllDel.length != 0) {
      selectAllDel.forEach(item => {
        console.log(item);
        fs.unlink(
          path.join(__dirname, "../public/images/fwImg/" + item),
          function(error) {
            if (error) {
              console.log(error);
              return false;
            }
            console.log("删除文件成功");
          }
        );
      });
    }

    console.log("````article找出删除图片````");
    console.log(htmlDelectId);
    console.log("````线上文章图片找出删除图片````");
    console.log(onlineDele);
    console.log("````总共找出删除图片````");
    console.log(allDelect);
    console.log("````去重找出删除图片````");
    console.log(selectAllDel);

    //查询一级评论
    let commentData = await comment.find({
      articleid: deleData._id
    });
    console.log("````找出一级评论记录````");
    console.log(commentData);

    //删除二级评论
    for (let index = 0; index < commentData.length; index++) {
      const element = commentData[index];
      await comfabulous.deleteMany({
        commentid: element._id
      });
    }

    //删除一级评论
    await comment.deleteMany({
      articleid: deleData._id
    });

    //删除文章（珠海港圈）
    await answer.deleteOne({
      _id: deleData._id
    });

    res.json({
      code: 200,
      mess: "succse"
    });
  } catch (error) {
    console.log(error);
    res.json({
      code: 200,
      error
    });
  }
});

//删除文章（珠海港圈、创新建议）
router.post("/api/v1/delectArticle", async function(req, res, next) {
  let deleData = req.body;
  try {
    //文章图片
    let htmlDelectId = getRemovImgId(deleData.content);
    let headDeleId = deleData.articleimg.replace(rich_text_img_prefix, "");
    htmlDelectId.push(headDeleId);

    //删除并找出线上文章
    let articleOnlineDraftData = await articleOnlineDraft.findOneAndDelete({
      articleId: deleData._id
    });

    let onlineDele = [];
    if (articleOnlineDraftData) {
      let onliveHtmlDelectId = getRemovImgId(articleOnlineDraftData.content);
      onlineDele = articleOnlineDraftData.deleImgId.concat(
        articleOnlineDraftData.deletTitleImageUrl,
        articleOnlineDraftData.deleImgId,
        onliveHtmlDelectId
      );
    }

    //总图片
    let allDelect = onlineDele.concat(htmlDelectId);

    //去重
    let selectAllDel = [...new Set(allDelect)];
    //删除图片
    selectAllDel.forEach(item => {
      console.log(item);
      fs.unlink(
        path.join(__dirname, "../public/images/fwImg/" + item),
        function(error) {
          if (error) {
            console.log(error);
            return false;
          }
          console.log("删除文件成功");
        }
      );
    });

    console.log("````article找出删除图片````");
    console.log(htmlDelectId);
    console.log("````线上文章图片找出删除图片````");
    console.log(onlineDele);
    console.log("````总共找出删除图片````");
    console.log(allDelect);
    console.log("````去重找出删除图片````");
    console.log(selectAllDel);

    //删除历史记录
    let historyData = await history.deleteMany({
      articleid: deleData._id
    });
    //查询一级评论
    let commentData = await comment.find({
      articleid: deleData._id
    });
    console.log("````找出一级评论记录````");
    console.log(commentData);

    //删除二级评论
    for (let index = 0; index < commentData.length; index++) {
      const element = commentData[index];
      await comfabulous.deleteMany({
        commentid: element._id
      });
    }

    //删除一级评论
    await comment.deleteMany({
      articleid: deleData._id
    });

    //删除文章（珠海港圈）
    await article.deleteOne({
      _id: deleData._id
    });

    //删除推荐
    await recommend.deleteOne({
      articleid: deleData._id
    });

    res.json({
      code: 200,
      mess: "succse"
    });
  } catch (error) {
    console.log(error);
    res.json({
      code: 200,
      error
    });
  }
});

//删除文章（资源共享）
router.post("/api/v1/delectResource", async function(req, res, next) {
  let deleData = req.body;
  try {
    //文章图片
    let htmlDelectId = getRemovImgId(deleData.content);

    //删除并找出线上文章
    let resourceOnlineDraftData = await resourceOnlineDraft.findOneAndDelete({
      articleId: deleData._id
    });

    let onlineDele = [];
    if (resourceOnlineDraftData) {
      let onliveHtmlDelectId = getRemovImgId(resourceOnlineDraftData.content);
      onlineDele = resourceOnlineDraftData.deleImgId.concat(
        resourceOnlineDraftData.deleImgId,
        onliveHtmlDelectId
      );
    }

    //总图片
    let allDelect = onlineDele.concat(htmlDelectId);

    //去重
    let selectAllDel = [...new Set(allDelect)];

    console.log("````article找出删除图片````");
    console.log(htmlDelectId);
    console.log("````线上文章图片找出删除图片````");
    console.log(onlineDele);
    console.log("````总共找出删除图片````");
    console.log(allDelect);
    console.log("````去重找出删除图片````");
    console.log(selectAllDel);

    //删除图片
    if (selectAllDel.length != 0) {
      selectAllDel.forEach(item => {
        console.log(item);
        fs.unlink(
          path.join(__dirname, "../public/images/fwImg/" + item),
          function(error) {
            if (error) {
              console.log(error);
              return false;
            }
            console.log("删除图片成功");
          }
        );
      });
    }

    //文章附件
    let delectResourceFile = [];
    if (deleData.filesName) {
      delectResourceFile.push(deleData.filesName);
    }

    //线上附件
    if (
      resourceOnlineDraftData &&
      resourceOnlineDraftData.fileList.length != 0
    ) {
      delectResourceFile.push(resourceOnlineDraftData.fileList[0].filesName);
      delectResourceFile = delectResourceFile.concat(
        resourceOnlineDraftData.fileDelectArr
      );
    }

    let allDeleResourceFile = delectResourceFile;

    let selectAllDeleResourceFile = [...new Set(allDeleResourceFile)];
    console.log("````总共找出附件````");
    console.log(allDeleResourceFile);
    console.log("````去重找出附件图片````");
    console.log(selectAllDeleResourceFile);
    if (selectAllDeleResourceFile.length != 0) {
      selectAllDeleResourceFile.forEach(item => {
        console.log(item);
        fs.unlink(path.join(__dirname, "../public/enclosure/" + item), function(
          error
        ) {
          if (error) {
            console.log(error);
            return false;
          }
          console.log("删除附件成功");
        });
      });
    }

    //删除历史记录
    let historyData = await history.deleteMany({
      articleid: deleData._id
    });
    //查询一级评论
    let commentData = await comment.find({
      articleid: deleData._id
    });
    console.log("````找出一级评论记录````");
    console.log(commentData);

    //删除二级评论
    for (let index = 0; index < commentData.length; index++) {
      const element = commentData[index];
      await comfabulous.deleteMany({
        commentid: element._id
      });
    }

    //删除一级评论
    await comment.deleteMany({
      articleid: deleData._id
    });

    //删除文章（资源共享）
    await resource.deleteOne({
      _id: deleData._id
    });

    //删除推荐
    await recommend.deleteOne({
      resourceid: deleData._id
    });

    res.json({
      code: 200,
      mess: "succse"
    });
  } catch (error) {
    console.log(error);
    res.json({
      code: 200,
      error
    });
  }
});

// 导出模块（在 app.js 中引入）
module.exports = router;
